<script>
import { reactive, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getSessionStorage } from "../common.js";
import axios from "axios";
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    setup() {
        const router = useRouter();
        const route = useRoute();
        const state = reactive({
            orderId: route.query.orderId,
            doctor: getSessionStorage('doctor'),
            overallResultArr: [],
            overallResultForm: {
                title: "",
                content: "",
            },
            updateOverallResultForm: {
                orId: "",
                title: "",
                content: "",
            },
            state: route.query.state,
            orders: {
                users: {},
                setmeal: {}
            },
            users: {
                userId: '',
                password: '',
                realName: '',
                sex: '',
                indentityCard: '',
                birthday: '',
                userType: ''
            },
            ciReportArr: [],
            dialogVisible: false,
        });


        //初始化查询-体检预约信息
        getOrdersById();


        //初始化查询-体检报告检查项信息
        listCiReport();
        //初始化查询-总检结论项信息
        listOverallResultByOrderId();

        // 根据传递的orderId查询得到orders数据
        function getOrdersById() {
            // console.log("这是预约编号：" + state.orderId);//可以得到orderId
            axios.post("/api/orders/getOrdersById", {
                orderId: state.orderId,
            }).then((response) => {
                console.log("getOrdersById:", response);//可得到
                state.orders = response.data;
                console.log("state.orders:", state.orders.orderId);//可得到

                state.orders.orderDate = moment(state.orders.orderDate).format('YYYY-MM-DD')
                // 初始化查询-用户信息
                getUsersById(state.orders.userId); // 传递 userId
                getSetmealById(state.orders.setmeal);

            }).catch((error) => {
                console.error(error);
            });
        }

        // 根据传递的orderId查询得到orders数据
        function getUsersById() {

            // console.log("这是用户信息：", state.orders.userId);//可以得到
            axios.post("/api/users/select", {
                userId: state.orders.userId, // 传递 userId
            }).then((response) => {
                console.log("getUsersById:", response);//可得到
                state.orders.users = response.data.data; // 将用户信息赋值给 orders.users
                console.log("根据getUsersById的response得到的用户信息为:", state.orders.users);//可得到
            }).catch((error) => {
                console.error(error);
            });
        }

        function getSetmealById() {

            // console.log("这是用户信息：", state.orders.userId);//可以得到
            axios.post("/api/setmeal/getSetmealById", {
                smId: state.orders.smId, // 传递 smId
            }).then((response) => {
                console.log("getSetmealById:", response);//可得到
                state.orders.setmeal = response.data.data; // 将用户信息赋值给 orders.users
                console.log("根据getSetmealById的response得到的套餐信息为:", state.orders.setmeal);//可得到
            }).catch((error) => {
                console.error(error);
            });
        }

        // 显示套餐明细
        function listCiReport() {
            axios.post("/api/ciReport/listCiReport", { orderId: state.orderId }).then((response) => {
                // console.log("listCiReport.response", response);//可获得
                state.ciReportArr = response.data;//报告明细
            }).catch((error) => {
                console.error(error);
            });
        }

        function updateCiDetailedReport(ciIndex) {
            //表单验证（1：非空；2：当type==1时验证是否为数字）
            let cidrArr = state.ciReportArr[ciIndex].cidrList;
            console.log("updateCiDetailedReport", cidrArr);

            for (let i = 0; i < cidrArr.length; i++) {
                console.log("第几个：" + i);

                if (cidrArr[i].value == null || cidrArr[i].value == "") {
                    // alert(cidrArr[i].name + "不能为空！");
                    ElMessage({
                        type: 'warning',
                        message: cidrArr[i].name + '不能为空！',
                    })
                    return;
                }
                if (
                    cidrArr[i].type == 1 &&
                    isNaN(parseFloat(cidrArr[i].value))
                    // parseFloat(cidrArr[i].value).toString() == "NaN"
                ) {
                    // alert(cidrArr[i].name + "必须为数字！");
                    ElMessage({
                        type: 'warning',
                        message: cidrArr[i].name + '必须是数字',
                    })
                    return;
                }
            }

            //封装提交参数（压缩提交参数）
            let arr = [];
            for (let i = 0; i < cidrArr.length; i++) {
                arr.push({
                    cidrId: cidrArr[i].cidrId,
                    value: cidrArr[i].value,
                    isError: cidrArr[i].isError,
                });
            }

            axios.post("/api/ciDetailedReport/updateCiDetailedReport", arr).then((response) => {
                console.log(response.data)
                if (response.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '保存成功！',
                    })
                    listCiReport();
                } else {
                    ElMessage({
                        type: 'error',
                        message: '保存失败！',
                    })
                }
            }).catch((error) => {
                console.error(error);
            });
        }

        function listOverallResultByOrderId() {
            axios.post("/api/OverallResult/listOverallResultByOrderId", {
                orderId: state.orderId,
            }).then((response) => {
                state.overallResultArr = response.data;
                for (let i = 0; i < state.overallResultArr.length; i++) {
                    state.overallResultArr[i].code = i + 1;
                }
            }).catch((error) => {
                console.error(error);
            });
        }

        function toOrdersList() {
            console.log("查询体检用户");
            router.push("/reportList");
        }

        function cidrCheckByBlur(ciIndex, cidrIndex) {
            //获取当前选中的检查项明细
            let cidr = state.ciReportArr[ciIndex].cidrList[cidrIndex];
            //判断type属性（1：数值范围验证型；2：数值相等验证型；）
            if (cidr.type == 1) {
                if (
                    !(cidr.value == null || cidr.value == "") &&
                    (cidr.value < cidr.minrange || cidr.value > cidr.maxrange)
                ) {
                    cidr.isError = 1;
                } else {
                    cidr.isError = 0;
                }
            } else if (cidr.type == 2) {
                if (
                    !(cidr.value == null || cidr.value == "") &&
                    cidr.value != cidr.normalValue
                ) {
                    cidr.isError = 1;
                } else {
                    cidr.isError = 0;
                }
            }
        }

        listoverallResultForm()
        function listoverallResultForm() {
            axios
                .post("/api/OverallResult/listOverallResultByOrderId", {
                    orderId: state.orderId,
                })
                .then((response) => {
                    console.log("listOverallResultByOrderId:" + response.data)
                    state.overallResultArr = response.data;
                    for (let i = 0; i < state.overallResultArr.length; i++) {
                        state.overallResultArr[i].code = i + 1;
                    }
                })
                .catch((error) => {
                    console.error(error);
                });

        }


        function addOverallResult() {
            if (state.updateOverallResultForm.title == "") {
                ElMessage({
                    type: 'error',
                    message: '总检结论项标题不能为空！',
                })
                return;
            }
            if (state.updateOverallResultForm.content == "") {
                ElMessage({
                    type: 'error',
                    message: '总检结论项内容不能为空！',
                })
                return;
            }

            state.updateOverallResultForm.orderId = state.orderId;
            console.log("state.updateOverallResultForm.orId:" + state.updateOverallResultForm.orderId)
            console.log("state.updateOverallResultForm.title:" + state.updateOverallResultForm.title)
            console.log("state.updateOverallResultForm.content:" + state.updateOverallResultForm.content)

            axios
                .post("/api/OverallResult/saveOverallResult", state.updateOverallResultForm)
                .then((response) => {
                    if (response.data > 0) {
                        console.log("response.data:" + response.data)
                        ElMessage({
                            type: 'success',
                            message: '添加成功！',
                        })

                        listOverallResultByOrderId();
                        state.updateOverallResultForm.title = "",
                            state.updateOverallResultForm.content = ""
                        return;
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '总检结论项添加失败！',
                        })
                    }
                })
                .catch((error) => {
                    console.error(error);
                });
        }

        function resetOverallResult() {
            state.overallResultForm = {
                title: "",
                content: "",
            };
        }

        function removeOverallResult(row) {

            ElMessageBox.confirm(
                '确认删除此数据吗？',
                '删除数据',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning', // 注意这里的 'warning' 应该小写
                }
            ).then(() => {
                // 用户点击确认后的操作
                ElMessage({
                    type: 'success',
                    message: '删除成功！',
                });

                axios
                    .post("/api/OverallResult/removeOverallResult", {
                        orId: row.orId,
                    })
                    .then((response) => {
                        if (response.data > 0) {
                            listOverallResultByOrderId();
                        } else {
                            ElMessage({
                                type: 'error',
                                message: '总检结论项删除失败！',
                            })

                        }
                    })
                    .catch((error) => {
                        console.error(error);
                    });
            }).catch(() => {
                // 用户点击取消后的操作
                ElMessage({
                    type: 'info',
                    message: '已取消删除！',
                });
            });




        }

        function toUpdateOverallResult(row) {
            state.dialogVisible = true;
            //这里不能直接赋值为row，必须使用深拷贝。否则更新数据与原数据是绑定的
            state.updateOverallResultForm = JSON.parse(JSON.stringify(row));
        }

        function updateOrdersState() {

            ElMessageBox.confirm(
                '总检结论报告归档前，请务必确认是否所有检查项数据都正确？',
                '总检结论报告归档',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning', // 注意这里的 'warning' 应该小写
                }
            ).then(() => {
                // 用户点击确认后的操作
                ElMessage({
                    type: 'success',
                    message: '总检结论报告归档成功！',
                });

                axios
                    .post("/api/orders/updateOrdersState", {
                        orderId: state.orderId,
                        state: 2
                    })
                    .then((response) => {
                        if (response.data > 0) {
                            router.push('/reportList');
                        } else {
                            ElMessage({
                                type: 'error',
                                message: '总检结论报告归档失败！',
                            })
                        }
                    })
                    .catch((error) => {
                        console.error(error);
                    });


            }).catch(() => {
                // 用户点击取消后的操作
                ElMessage({
                    type: 'info',
                    message: '已取消总检结论报告归档！',
                });
            });


        }

        function toclear() {
            state.updateOverallResultForm.title = "",
                state.updateOverallResultForm.content = ""
        }

        return {
            ...toRefs(state),
            getOrdersById,
            getUsersById,
            listCiReport,
            listOverallResultByOrderId,
            cidrCheckByBlur,
            getSetmealById,
            updateCiDetailedReport,
            toOrdersList, addOverallResult,
            listoverallResultForm,
            resetOverallResult,
            toclear, //清空
            updateOrdersState,
            removeOverallResult, toUpdateOverallResult

        };
    },
};
</script>



<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <h1>Neusoft &nbsp;&nbsp;&nbsp;东软体检报告管理系统</h1>
                <p>医生：{{ doctor.realName }}</p>
            </el-header>
            <el-container>
                <el-aside width="260px">
                    <el-descriptions class="margin-top" title="预约客户信息" :column="1" border>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">预约编号</div>
                            </template>
                            {{ orders.orderId }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">手机号码</div>
                            </template>
                            {{ orders.userId }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">真实姓名</div>
                            </template>
                            {{ orders.users && orders.users.realName ? orders.users.realName : '加载中...' }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">性别</div>
                            </template>
                            {{ orders.users && orders.users.sex !== undefined ? (orders.users.sex === 1 ? '男' : '女') :
                                '加载中...' }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">套餐类型</div>
                            </template>
                            {{ orders.setmeal && orders.setmeal.name ? orders.setmeal.name : '加载中...' }}

                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">体检日期</div>
                            </template>
                            {{ orders.orderDate || '加载中...' }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-button type="primary" style="margin-top: 20px" @click="toOrdersList">查询体检用户</el-button>
                </el-aside>
                <el-main>
                    <div class="main-box">
                        <el-collapse>
                            <el-collapse-item :title="ci.ciName" v-for="(ci, ciIndex) in ciReportArr" :key="ci.ciId">
                                <el-row style="color: #888">
                                    <el-col :span="12" style="box-sizing: border-box; padding: 6px 10px"
                                        v-for="(cidr, cidrIndex) in ci.cidrList" :key="cidr.ciId">
                                        <span style="
                                            background-color: #ba634e;
                                            color: #fff;
                                            box-sizing: border-box;
                                            padding: 1px 3px;
                                            border-radius: 3px;
                                            margin-right: 5px;
                                            " v-if="cidr.isError == 1">异</span>

                                        <span style="margin-right: 5px; vertical-align: top">
                                            {{ cidr.name }}
                                        </span>

                                        <el-input style="width: 26%; margin-right: 2px" size="small"
                                            :placeholder="cidr.name" v-if="cidr.type != 4"
                                            v-model="ciReportArr[ciIndex].cidrList[cidrIndex].value"
                                            @blur="cidrCheckByBlur(ciIndex, cidrIndex)" />
                                        <el-input style="width: 80%" type="textarea" :rows="2" :placeholder="cidr.name"
                                            v-model="ciReportArr[ciIndex].cidrList[cidrIndex].value"
                                            v-if="cidr.type == 4" />

                                        <span style="margin-right: 15px">{{ cidr.unit }}</span>

                                        <span v-if="cidr.normalValueString">正常值范围: {{ cidr.normalValueString }}</span>
                                    </el-col>
                                </el-row>
                                <el-button type="primary" style="margin-top: 8px"
                                    @click="updateCiDetailedReport(ciIndex)" v-if="orders.state == 1">{{ ci.ciName
                                    }}项保存</el-button>
                            </el-collapse-item>
                        </el-collapse>


                        <el-card style="width: auto; margin-top: 10px;">
                            <template #header>
                                <div class="card-header">
                                    <span>总检结论</span>
                                    <el-button type="danger" @click="updateOrdersState"
                                        v-if="orders.state == 1">体检套餐总检结果报告归档</el-button>
                                </div>
                            </template>
                            <!-- v-model="dialogVisible" title="总检结论项更新"updateOverallResultForm.orId
                          updateOverallResultForm.title updateOverallResultForm.content -->
                            <el-table :data="overallResultArr" style="width: 100%">
                                <el-table-column fixed prop="code" label="编号" width="60" />
                                <el-table-column prop="title" label="总检结论项标题" width="250" />
                                <el-table-column prop="content" label="总检结论项内容" width="500" />
                                <el-table-column fixed="right" label="操作" min-width="220" v-if="state == 1">
                                    <template #default="scope">
                                        <el-button link type="primary" size="small"
                                            @click="removeOverallResult(scope.row)" v-if="state == 1">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <div :model="updateOverallResultForm"
                                style="margin-top: 20px;font-size: 13px; color: #888;">
                                <el-form-item label="总检结论项标题" v-if="state == 1">
                                    <el-input v-model="updateOverallResultForm.title"></el-input>
                                </el-form-item>
                                <el-form-item label="总检结论项内容" v-if="state == 1">
                                    <!-- <el-input type="textarea" /> -->
                                    <el-input v-model="updateOverallResultForm.content" type="textarea"
                                        :rows="3"></el-input>
                                </el-form-item>
                                <el-form-item style="margin-left: 110px;margin-top: 30px;">
                                    <el-button type="primary" @click="addOverallResult" v-if="state == 1">添加</el-button>
                                    <el-button type="warning" @click="toclear" v-if="state == 1">清空</el-button>
                                </el-form-item>
                            </div>

                        </el-card>

                    </div>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>



<style scoped>
.el-header {
    background-color: #B3C0D1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #1c51a3;
}

.el-header h1 {
    font-size: 22px;
    font-weight: 700;
}

.el-header p {
    font-size: 16px;
}

.el-aside {
    background-color: #D3DCE6;
    box-sizing: border-box;
    padding: 20px;
}

.el-aside h4 {
    color: #555;
    margin-bottom: 10px;
}

.el-main {
    background-color: #fff;
}

/*********** 描述列表 ***********/

.el-descriptions {
    margin-top: 20px;
}

.cell-item {
    display: flex;
    align-items: center;
}

.margin-top {
    margin-top: 20px;
}

/*********** 总检结论 ***********/
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.box-card {
    width: 100%;
}
</style>